import React, {useState, useEffect} from 'react';
import {
  StyleSheet,
  Text,
  View,
  TouchableOpacity,
  Platform,
  PermissionsAndroid,
} from 'react-native';

import {Button} from '@rneui/themed';
import DeviceInfo from 'react-native-device-info';
import {connect} from 'react-redux';
import layoutStyle from '@/assets/styles/layout';
import Overlay from '@/components/Overlay';
import Toast from 'react-native-root-toast';
import RNFetchBlob from 'rn-fetch-blob';
import {getLatestAppApkVersion, getLatestAppApkDownloadUrl} from '@/apis/api';
import {
  APP_CODE as appCode,
  BASE_URL as baseUrl,
  DEVICE_TYPE as deviceType,
  APP_NAME as appName,
  VERSION_NAME as versionName,
} from '../../../app.json';
import {useTranslation} from 'react-i18next';
let AboutMeScreen = ({navigation}) => {
  const {t} = useTranslation();
  let [version, setVersion] = useState(versionName);
  let [appName, setAppName] = useState('');
  let [latesetVersion, setLatesetVersion] = useState(versionName);
  let [downloadUrl, setDownloadUrl] = useState('');
  const [showBtn, setShowBtn] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [storage, setStorage] = useState(true);

  const getLatestUpgradeVersion = () => {
    const data = {
      appCode,
      baseUrl,
      deviceType,
      versionName,
    };
    // 获取最新的安装包版本
    getLatestAppApkVersion(data).then(res => {
      setLatesetVersion(res?.data || versionName);
      if (res?.data && res?.data !== versionName) {
        // 存在新版本
        const params = {
          appCode,
          baseUrl,
          deviceType,
          versionName: res?.data || versionName,
        };
        getLatestAppApkDownloadUrl(params).then(res => {
          if (res?.data) {
            setShowBtn(true);
            setDownloadUrl(res.data);
          } else {
            setShowBtn(false);
          }
        });
      }
    });
  };

  const crequestMultiplePermission = async () => {
    try {
      const permissions = [
        PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
        PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
      ];
      const granteds = await PermissionsAndroid.requestMultiple(permissions);
      if (granteds['android.permission.READ_EXTERNAL_STORAGE'] === 'granted') {
        setStorage(true);
      } else {
        setStorage(false);
      }
    } catch (err) {
      console.log(err);
    }
  };

  const download = async () => {
    crequestMultiplePermission();
    const android = RNFetchBlob.android;
    let timestamp = new Date().getTime();

    // 指定包含最新版本的安装包文件的 URL
    const fileUrl = downloadUrl;
    // 文件保存路径
    const downloadDest = `${RNFetchBlob.fs.dirs.DownloadDir}/${appCode}-${timestamp}.apk`;
    setIsLoading(true);
    RNFetchBlob.config({
      fileCache: true,
      addAndroidDownloads: {
        useDownloadManager: true,
        // notification: true,
        mediaScannable: true,
        title: `${appCode}-${timestamp}.apk`,
        path: downloadDest,
      },
    })
      .fetch('GET', fileUrl, {})
      .then(res => {
        //下载成功后自动打开安装已下载apk文件
        setIsLoading(false);
        android.actionViewIntent(
          res.path(),
          'application/vnd.android.package-archive',
        );
        console.log('The file saved to ', res.path());
      })
      .catch(error => {
        setIsLoading(false);
        Toast.show(t('sys_packageDownloadFail'), {
          duration: 1000,
          position: Toast.positions.CENTER,
        });
      });
  };
  useEffect(() => {
    navigation.setOptions({
      headerShown: true,
      headerBackVisible: true,
    });
    setVersion(DeviceInfo.getVersion());
    setAppName(DeviceInfo.getApplicationName());
    getLatestUpgradeVersion();
  }, []);

  return (
    <View style={[layoutStyle.container, styles.container]}>
      <Overlay isShow={isLoading} />
      <View style={styles.bodybox}>
        <View style={styles.bodyboxFooter}>
          <Text style={styles.bodyboxTopText}>
            {t('sys_appNameWithColon')}
            {appName}
          </Text>
        </View>
        <View style={styles.bodyboxFooter}>
          <Text style={styles.bodyboxTopText}>
            {t('sys_appCodeWithColon')}
            {appCode}
          </Text>
        </View>
        <View style={styles.bodyboxFooter}>
          <Text style={styles.bodyboxFooterText}>
            {t('sys_currentVersionWithColon')}V{version}
          </Text>
        </View>
        <View style={styles.bodyboxFooter}>
          <Text style={styles.bodyboxFooterText}>
            {t('sys_newestVersionWithColon')}V{latesetVersion}
          </Text>
        </View>

        {showBtn ? (
          <View style={styles.bodyboxFooter}>
            <Text>
              <Button
                buttonStyle={{paddingHorizontal: 0}}
                type="clear"
                radius={'md'}
                title={t('sys_downloadNewVersionPackage')}
                onPress={download}
              />
            </Text>
          </View>
        ) : null}
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
  bodybox: {
    marginBottom: 30,
    marginLeft: 20,
    marginTop: 40,
  },
  bodyboxTop: {
    paddingTop: 40,
  },
  bodyboxFooter: {
    paddingBottom: 25,
  },
  bodyboxTopText: {
    fontWeight: '600',
    color: '#444',
    marginTop: 8,
  },
  bodyboxFooterText: {
    color: '#999',
  },
});

export default connect()(AboutMeScreen);
